<template>
  <div class="mail-detail">
    <div class="mail-header">

      <el-button type="text" @click="handleBack">返回</el-button>
      <el-button type="text" @click="handleDelete">删除</el-button>
      <el-button type="text" @click="handleReply" v-show="this.folderTo!==3">回复</el-button>
    </div>
    <div class="mail-main">
      <div class="start">
        <div style="width: 20%">
          <h2>{{ email.subject }}</h2>
        </div>
        <div style="left: auto">
          <el-button type="text" @click="handleStarred(email)">
            <el-icon
                v-if="email.isstarred === 1"
                class="is-dstarred"
                name="star-on"
            ></el-icon>
            <el-icon
                v-else
                class="is-not-dstarred"
                name="star-off"
            ></el-icon>
          </el-button>
        </div>
      </div>
    <p>发件人: {{ email.fromMail }}</p>
    <p>时间: {{ email.sendtime }}</p>
    <p>收件人: {{ email.toMail }}</p>
    <p v-if="attachments.length > 0">附  件:{{attachments.length}}个</p>
    <div v-html="email.content"></div>
      <el-divider></el-divider>
    </div>

    <div v-if="attachments.length > 0" class="mail-attachment">
     <el-icon-paperclip><h3>附件</h3></el-icon-paperclip>
      <el-row v-for="attachment in attachments" :key="attachment.attachmentId">
      <el-col :span="24">
        <el-link :href="attachment.storagePath" target="_blank" >
          <el-button type="text" @click="downloadFile(attachment)">
            {{ attachment.fileName }}
          </el-button></el-link>
      </el-col>
    </el-row>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {mapActions, mapGetters, mapState} from "vuex";
import MailboxList from "@/views/Mailbox/MailboxList.vue";
import MailboxSidebar from "@/views/Mailbox/MailboxSidebar.vue";
import MailboxHome from "@/views/Mailbox/MailboxHome.vue";
import ContactList from "@/views/Contact/ContactList.vue";

export default {
  name: 'MailDetail',
  inject: ['reload'],
  props: ['id'],
  data() {
    return{
      email:null,
      attachments:[],

    }

  },
  computed: {
    ...mapState(['emailId']) ,// 使用mapState辅助函数从Vuex获取currentId状态
    ...mapGetters(['folderTo']),
    ...mapState(['currentComponent']),
  },
  created() {
    this.fetchMailDetail(this.emailId);
    this.fetchAttachment(this.emailId);
  },
  methods: {
    ...mapActions['replaceComponent'],
   async fetchMailDetail(id) {
      // 假设 fetchMailDetail 是一个返回 Promise 的函数，用于从后端获取邮件详情
      console.log(id)
      axios.get('http://localhost:8989/email/content/'+id)
          .then(email => {
          this.email = email.data;
          console.log("emailstar"+ this.email.isstarred);
          }).catch(error => {
        console.error('Error fetching mail detail:', error);
      });
    },
   async fetchAttachment(id) {
      // 假设 fetchMailDetail 是一个返回 Promise 的函数，用于从后端获取邮件详情
      console.log(id)
      axios.get('http://localhost:8989/attachment/list/'+id)
          .then(attachment=> {
            this.attachments=attachment.data;
            for (let i = 0; i < this.attachments.length; i++){
              this.attachments[i].fileName = this.attachments[i].fileName.substring(this.attachments[i].fileName.indexOf(".")+1);

            }
            console.log("attachments"+ this.attachments);
          }).catch(error => {
        console.error('Error fetching mail detail:', error);
      });
    },
    handleDelete(){

    },
    handleStarred(email) {
      // 切换邮件的星标状态
      console.log("email.isstarred " + email.isstarred);

      if (email.isstarred===1) {
        console.log("ID1"+email)

        // 如果邮件已星标，则取消星标
        this.unStarred(email);
        email.isstarred=0;
        this.reload;
      }else if(email.isstarred===0){
        console.log("ID0 "+email.emailId)
        this.Starred(email);
        email.isstarred=1;
        this.reload;

      }
    },
    unStarred(email){
      axios.post('http://localhost:8989/email/unstar?emailId='+email.emailId)
          .then((response) => {
            console.log(response.data);
            this.getEmailList();
            console.log("UUisstarred"+email.isstarred);

          })
          .catch((error) => {
            console.error(error);
          });

    },
    Starred(email){
      axios.post('http://localhost:8989/email/star?emailId='+email.emailId)
          .then((response) => {
            console.log(response.data);
            this.getEmailList();
            console.log("SSisstarred"+email.isstarred);
          })
          .catch((error) => {
            console.error(error);
          });

    },
    handleBack() {
       this.$router.go(-1);
      // 获取当前路由的 params 中的 mailboxList id
      // 编程式导航到 mailboxList/id
      // const componentName = 'MailboxList';
      // console.log("componentName"+componentName);
      // this.$emit('back-clicked');
      // console.log("handleBack");
      // this.replaceComponent('MailboxList');
      //   // console.log(this.currentComponent);
      // console.log("页面"+this.currentComponent);
      //   this.$router.push({name: 'MailboxList', params: {folderId: this.folderTo}});
      //   this.reload();

    },
    async downloadFile(attachment) {
      alert("开始下载")
      var url = 'http://localhost:8989/attachment/download/'+attachment.attachmentId;
      window.open(url)
    },
    handleReply(){
      this.$router.push({ name: 'ReplyDetail', params: { id: this.emailId } });


    },


},
  watch: {

  }
};
</script>
<style>
.mail-detail{


}
.mail-main{
  text-align: left;
}
.mail-attachment{
  text-align: left;

}
.start{
  display: flex;
  justify-content: left;
  margin-right:auto;
}
.is-dstarred {
  color: #fce55f; /* 已星标颜色 */
  font-size: 40px;
}
.is-not-dstarred {
  color: #ccc; /* 未星标颜色 */
  font-size: 40px;
}
</style>